package io.xxx.xbutler.core.alarm;

import com.alibaba.fastjson2.JSONObject;
import io.xxx.xbutler.core.check.CheckError;
import io.xxx.xbutler.domain.task.MessageType;
import io.xxx.xbutler.domain.task.PushContext;
import io.xxx.xbutler.domain.task.Task;
import io.xxx.xbutler.domain.task.TaskItem;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 这个是默认的Alarm，在控制台打印错误信息。
 */
@Slf4j
public class ConsoleAlarm implements Alarm {

    @Override
    public boolean supports(PushContext context, CheckError error) {
        return true;
    }

    @Override
    public void alert(PushContext context, CheckError error) {
        Task task = context.getTask();
        List<TaskItem> items = context.getTaskItems();
        List<String> list = items.stream()
                .map(it -> {
                    MessageType messageType = it.getMessageType();
                    JSONObject content = it.getContent();
                    String msg = switch (messageType) {
                        case TEXT -> content.getString("text");
                        case IMAGE, VIDEO, CHANNEL -> content.getString("url");
                        case MINI_PROGRAM -> content.getString("title");
                    };
                    return messageType + ": " + msg;
                })
                .toList();
        StringBuilder builder = new StringBuilder(error.getErrorMessage())
                .append("[").append(error.getErrorCode()).append("]");
        builder.append(task.getName()).append("(").append(task.getId()).append(")").append("\n");
        for (int i = 0; i < list.size(); i++) {
            String s = list.get(i);
            builder.append(i).append(". ").append(s);
        }
        log.error(builder.toString());
    }
}
